<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 *
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 *
 * @package      FeatherCMS
 * @subpackage   Helpers
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class RssHelper
{
	public $channel    = array();
	public $items      = array();
	public $namespaces = array(
		'creativeCommons' => 'http://backend.userland.com/creativeCommonsRssModule'
	);
	
	// data
	
	function addNamespace($name, $resource)
	{
		$this->namespaces[$name] = $resource;
	}
	
	function setChannel($channel)
	{
		$this->channel = array(
			'title'         => 'NC',
			'link'          => FULL_BASE_URL,
			'description'   => 'NC',
			'lastBuildDate' => Timer::toRSS(time()),
			'generator'     => 'Feather for PHP 2',
			'docs'          => 'http://blogs.law.harvard.edu/tech/rss'
		);
		$this->channel = array_merge($this->channel, $channel);
	}
	
	function addItem($item)
	{
		array_push($this->items, $item);
	}
	
	// render
	
	function toString()
	{
		ob_start();
		
		// title
#		echo DEBUG ? '<rsss version="2.0"' : '<rss version="2.0"';
		echo '<rss version="2.0"';
		foreach($this->namespaces as $k => $v) {
			echo " xmlns:$k=\"$v\"";
		}
		echo '>';
		
		// channel
		echo '<channel>';
		$this->__parse($this->channel);
		
		// items
		foreach($this->items as $item)
		{
			echo '<item>';
			$this->__parse($item);
			echo '</item>';
		}
		
		echo '</channel></rss>';
#		echo DEBUG ? '</channel></rsss>' : '</channel></rss>';
		
		return ob_get_clean();
	}
	
	// internals
	
	protected function __parse(&$data)
	{
		foreach($data as $tag => $d)
		{
			if (!is_array($d))
				$this->__tag($tag, $d);
			else
				$this->__tag($tag, null, $d);
		}
	}
	
	protected function __tag($tag, $content=null, $attr=array())
	{
		if ($tag == 'category' and is_null($content))
		{
			foreach($attr as $v)
				$this->__tag($tag, $v);
			return;
		}
		elseif ($tag == 'guid' and !preg_match('{^https?://}', $content)) {
			$attr['isPermaLink'] = 'false';
		}
		$attr = $this->__parseAttributes($attr);
		echo is_null($content) ?
			"<$tag$attr />" : "<$tag$attr>".htmlspecialchars($content)."</$tag>";
	}
	
	protected function __parseAttributes(&$attr)
	{
		if (empty($attr)) return null;
		$str = '';
		foreach ($attr as $p => $v)
		{
			$v = htmlspecialchars($v);
			$str .= " $p=\"$v\"";
		}
		return $str;
	}
}
?>